package com.tsingteng.cosfun.ui.costar;

import android.content.Intent;
import android.opengl.GLSurfaceView;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.pili.droid.shortvideo.PLDisplayMode;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLShortVideoComposer;
import com.qiniu.pili.droid.shortvideo.PLShortVideoEditor;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTrimmer;
import com.qiniu.pili.droid.shortvideo.PLVideoEditSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoFrame;
import com.qiniu.pili.droid.shortvideo.PLVideoPlayerListener;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BaseVideoActivity;
import com.tsingteng.cosfun.callback.OnDBSaveListener;
import com.tsingteng.cosfun.callback.OnInitGifListener;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.crashUtils.utils.FileUtils;
import com.tsingteng.cosfun.crashUtils.utils.LogUtil;
import com.tsingteng.cosfun.helper.ActivityManagers;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.costar.publish.VideoPublishActivity;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.Command;
import com.tsingteng.cosfun.utils.CommandManager;
import com.tsingteng.cosfun.utils.DBUtils;
import com.tsingteng.cosfun.utils.DesityUtils;
import com.tsingteng.cosfun.utils.FileUtil;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.StringUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.utils.UIUtils;
import com.tsingteng.cosfun.utils.VideoAddCommand;
import com.tsingteng.cosfun.utils.VideoSetCommand;
import com.tsingteng.cosfun.widget.ThumbnailView;
import com.tsingteng.cosfun.widget.dialog.BeautifyDialog;
import com.tsingteng.cosfun.widget.PressImageView;
import com.tsingteng.cosfun.widget.dialog.ContentDialog;
import com.tsingteng.cosfun.widget.dialog.CostarHintDialog;
import com.tsingteng.cosfun.widget.dialog.ProgressDialog;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 描述: 预览界面
 * 创建人: 肖利
 * 时间: 2018/7/31
 * qq: (872179966)
 */

public class PreViewActivity extends BaseVideoActivity implements View.OnClickListener, PLVideoPlayerListener, PLVideoSaveListener, BeautifyDialog.OnDialogDissMissListener,ThumbnailView.OnScrollBorderListener {
    private static final String TAG = "PreViewActivity";
    private RelativeLayout mRlPush;

    private ImageView mIvPre;
    private ImageView mIvNext;
    private ImageView mIvClose;
    private LinearLayout llToolsRight;
    private LinearLayout mMeiHua;
    private ProgressBar mSectionProgressBar;
    private GLSurfaceView mPreviewView;
    private String mMp4path;
    private PLShortVideoEditor mShortVideoEditor;
    private long mMixDuration = 0; // ms
    private RelativeLayout mRlFinish;


    private PLShortVideoEditorStatus mShortVideoEditorStatus = PLShortVideoEditorStatus.Idle;
    private PLVideoEditSetting setting;
    private LinearLayout mLlBotton;
    private Timer timerTask;
    private TimerTask taskTimer;
    private PLShortVideoComposer mShortVideoComposer;
    private BeautifyDialog beautifyDialog;

    private TextView mTvSave;
    private TextView mTvCancle;
    private LinearLayout mFrameListView;
    private PLShortVideoTrimmer mShortVideoTrimmer;
    private PLMediaFile mMediaFile;
    private RelativeLayout mRlViewJianji;
    private Handler mHandler = new Handler();
    private boolean videoType = false;
    private PressImageView mPrtotate;
    private int rotate = 0;
    private int handleType = 0;//1 保存 2拼接
    private TextView mMore;
    private boolean isCutVideo = false;
    private ImageView mIvPlay;
    private boolean isPlay = true;
    private ProgressDialog progressDialog;
    private ThumbnailView thumbnailView;
    private TextView haveSelectTime;
    private PLShortVideoTranscoder mShortVideoTranscoder;
    private boolean isLocal = false;
    private ImageView mIvSave;
    private ImageView mIvCancle;
    private boolean videoRotate;
    private boolean isSaveing = false;
    private long canHave;
    private RelativeLayout mRlfs;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pr_jj:
            case R.id.ll_jj:
                isLocal = false;
                CutOutVideo(true);
                break;
            case R.id.rl_push:
                isSaveing = true;
                handleType = 2;
                if (progressDialog == null) progressDialog = new ProgressDialog(this);
                progressDialog.show();
                mShortVideoEditor.save();
                finishCommonActivity();
                break;
            case R.id.iv_close:
                new ContentDialog(this).setContent("确定要放弃当前录制吗?").setCancelContent("取消")
                        .setAffirmContent("放弃").setAffirmContentColor(R.color.red_bag_color)
                        .setOnTwoClickListener(new ContentDialog.OnTwoClickListener() {
                            @Override
                            public void onAffirm() {
//                                finish();
                                ActivityManagers.getInstance().delShootActivity();
                                overridePendingTransition(R.anim.activity_up_alpha, R.anim.activity_down);
                            }

                            @Override
                            public void onCancel() {

                            }
                        }).show();

                break;
            case R.id.iv_next:
                Command redo = VideoHelper.getIntence().getCommendFilterManger().redo();
                if (redo == null) {
                    AppUtils.showHintDialogToast(this, "恢复失败!");
                    return;
                }
                VideoHelper.getIntence().getOperationFilter(2, this, redo);
                initFilterCommandManger();
                break;
            case R.id.iv_pre:
                Command undo = VideoHelper.getIntence().getCommendFilterManger().undo();
                if (undo == null) {
                    AppUtils.showHintDialogToast(this, "撤销失败!");
                    return;
                }
                VideoHelper.getIntence().getOperationFilter(1, this, undo);
                initFilterCommandManger();
                break;
            case R.id.pr_yf:
            case R.id.ll_yf:
                showToast("影范");
                break;
            case R.id.pr_mei_hua:
            case R.id.ll_mh:
                if (beautifyDialog == null)
                    beautifyDialog = new BeautifyDialog(this, null, mShortVideoEditor, 2);
                beautifyDialog.show();
                setVisibility(View.GONE, mRlFinish, mRlPush, llToolsRight, mSectionProgressBar);
                break;
            case R.id.ll_again_cos:
                new ContentDialog(this).setContent("确定要删除片段,重做吗?").setAffirmContent("删除").setAffirmContentColor(R.color.red_bag_color).setCancelContent("取消").setOnTwoClickListener(new ContentDialog.OnTwoClickListener() {
                    @Override
                    public void onAffirm() {
                        finish();
                    }

                    @Override
                    public void onCancel() {

                    }
                }).show();

                break;
            case R.id.rl_finish:
                isSaveing = true;
                handleType = 1;
                if (progressDialog == null) progressDialog = new ProgressDialog(this);
                progressDialog.show();
                mShortVideoEditor.save();
                finishCommonActivity();
                break;
            case R.id.tv_save:
                onDone();
                break;
            case R.id.tv_cancle:

                isCutVideo = false;
                mSelectedBeginMs = 0;
                mSelectedEndMs = mMixDuration;
                if (isLocal) {
                    finish();
                } else {
                    CutOutVideo(isCutVideo);
                }
                break;

            case R.id.iv_save:
                isSaveing = true;
                onDone();
                break;
            case R.id.iv_cancle:
                isCutVideo = false;
                mSelectedBeginMs = 0;
                mSelectedEndMs = mMixDuration;
                if (isLocal) {
                    Navigate.startLocalVideo(this);
                } else {
                    CutOutVideo(isCutVideo);
                }
                break;

            case R.id.pr_rotate_icon:
                isSaveing = true;
                //旋转
                initRotateView();
                break;
            case R.id.preview:
                if (isPlay) {
                    pausePlayback(true);
                    if (timerTask != null) {
                        taskTimer.cancel();
                    }
                } else {
                    startPlayback();
                    timerTask = null;
                    taskTimer = null;
                    LogUtils.e("countDownTimer444444", time + "");
                    startTimer();
                }
                isPlay = !isPlay;
                break;
        }
    }


    /**
     * 隐藏显示事件
     */
    private void setVisibility(int visibility, View... views) {
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(visibility);
        }
    }


    private void initRotateView() {
        // 获取源视频宽度
        int srcWidth = mShortVideoTranscoder.getSrcWidth();
        // 获取源视频高度
        int srcHeight = mShortVideoTranscoder.getSrcHeight();
        // 获取源视频码率
        int srcBitrate = VideoHelper.mEncodingBitrate;
        rotate = rotate + 90;
        if (progressDialog == null) progressDialog = new ProgressDialog(this);
        progressDialog.show();
        mShortVideoTranscoder.transcode(srcWidth, srcHeight, srcBitrate, rotate, false, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String s) {
                isSaveing = false;
                runOnUiThread(() -> {
                    progressDialog.disMissDialog();
//                    Intent intent = new Intent(PreViewActivity.this, PreViewActivity.class);
//                    intent.putExtra(VideoHelper.VIDEO_PATH, s);
//                    intent.putExtra(VideoHelper.VIDEO_ROTATE, true);
//                    intent.putExtra(VideoHelper.VIDEO_LOCAL, isLocal);
//                    startActivity(intent);
//                    finish();
                    setNewVideoPath(s);
                });
            }

            @Override
            public void onSaveVideoFailed(int i) {
                isSaveing = false;
                progressDialog.disMissDialog();
            }

            @Override
            public void onSaveVideoCanceled() {
                isSaveing = false;
                progressDialog.disMissDialog();
            }

            @Override
            public void onProgressUpdate(float percentage) {
                runOnUiThread(() -> {
                    if ((int) (100 * percentage) <= 100)
                        progressDialog.setmProgressbar((int) (100 * percentage));
                });
            }
        });


    }

    public void saveVideo() {
        //判断是否保存了视屏
        if (!VideoHelper.getIntence().isSaveVideo(mMp4path)) {
            saveVideoToBean();
            finish();
        } else {
            finish();
        }
    }

    /**
     * \
     * 保存视屏到bean
     */
    private void saveVideoToBean() {
        LogUtils.e(TAG, "完成后保存的地址为:mMp4path" + mMp4path);
        //得到当前的索引(当前的索引交由插入的时候重新赋值)
        int currentVideoPosition = VideoHelper.getIntence().getCurrentVideoPosition();
        //如果视屏索引==-1的话,说明是添加视频,直接在后面添加视频即可
        if (currentVideoPosition == -1) {
            VideoAddCommand videoAddCommand = new VideoAddCommand(VideoHelper.getIntence().getVideoInfoSize(), mMixDuration, mMp4path);
            VideoHelper.getIntence().getCommendManger().pushCommandAndApply(videoAddCommand);
//            VideoHelper.getIntence().addVideoInfo(mMp4path,mMixDuration);
        } else {//否则的话视屏就是翻拍的(不管是原生翻拍的还是自由翻拍,直接把翻拍的视屏插入到原有的地方,替换原先的视屏地址)
//            VideoHelper.getIntence().setVideoInfo(mMp4path,mMixDuration,currentVideoPosition);
            VideoSetCommand videoSetCommand = new VideoSetCommand(currentVideoPosition, mMixDuration, mMp4path);
            VideoHelper.getIntence().getCommendManger().pushCommandAndApply(videoSetCommand);
        }
        //将视屏保存到数据库中
//        boolean b = DBUtils.saveShootVideo(mMp4path, mMp4Time, false, VideoUtils.getIntance().getVideoType(), "");
        DBUtils.UpDataJoinBean(VideoHelper.getIntence().getVideoType(), VideoHelper.getIntence().getJoinCostarBean(), new OnDBSaveListener() {
            @Override
            public void onSaveSuccess() {

            }

            @Override
            public void onSaveFail() {
                AppUtils.showHintDialogToast(PreViewActivity.this, "保存草稿失败!");
            }
        });

    }


    /**
     * 合并视屏
     */
    private void conposeVideo() {
        //判断是否保存了视屏
        if (!VideoHelper.getIntence().isSaveVideo(mMp4path)) {
            saveVideoToBean();
        }

        if (VideoHelper.getIntence().getVideoListTime() < 5000) {
            CostarHintDialog costarHintDialog = new CostarHintDialog(this);
            costarHintDialog.show();
            new Handler().postDelayed(() -> costarHintDialog.dissMiss(), 1500);
            return;
        }
        //清空一下保存的空片段
        if (!VideoHelper.getIntence().clearEmptyVideoPath()) {
            new ContentDialog(this).setContent("发布失败,请重试!").setAffirmContent("我知道了!").setOnOneClickListener(() -> {

            }).show();
        } else {
            if (VideoHelper.getIntence().getVideoSectionBeanList().size() == 1) {
                initCompressVideo();
            } else {
                PLVideoEncodeSetting setting = new PLVideoEncodeSetting(this);
                setting.setEncodingSizeLevel(PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_3);
                setting.setEncodingBitrate(VideoHelper.mEncodingBitrate);
                List<String> list = VideoHelper.getIntence().getVideoPathList();
                try {
                    mShortVideoComposer.composeVideos(list, VideoHelper.VIDEO_COMPOSED + System.currentTimeMillis() + "compose.mp4", setting, mVideoSaveListener);
                    if (progressDialog == null) progressDialog = new ProgressDialog(this);
                    progressDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e("tag50", e.getMessage());
                }
            }

        }

    }

    private void initCompressVideo() {
        mShortVideoTranscoder = new PLShortVideoTranscoder(getApplicationContext(), VideoHelper.getIntence().getVideoSectionBeanList().get(0).getLocalUrl(), VideoHelper.VIDEO_STORAGE_DIR + System.currentTimeMillis() + LogonUtils.getProFildId() + "cos_fun.mp4");
        // 获取源视频宽度
        int srcWidth = mShortVideoTranscoder.getSrcWidth();
        // 获取源视频高度
        int srcHeight = mShortVideoTranscoder.getSrcHeight();
        // 获取源视频码率
        int srcBitrate = VideoHelper.mEncodingBitrate;
        if (progressDialog == null) progressDialog = new ProgressDialog(this);
        progressDialog.show();
        mShortVideoTranscoder.transcode(srcWidth, srcHeight, srcBitrate, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String destFile) {
                runOnUiThread(() -> {
                    progressDialog.disMissDialog();
                    ToVideoPushActivity(destFile);
//                        //将主视屏保存
//                        VideoHelper.getIntence().addMainVideoInfo(destFile);
//                        Intent intent = new Intent(PreViewActivity.this, VideoPublishActivity.class);
//                        startActivityForResult(intent, Constant.REQUESTCODE);
                });
            }

            @Override
            public void onSaveVideoFailed(int i) {
                progressDialog.disMissDialog();
            }

            @Override
            public void onSaveVideoCanceled() {
                progressDialog.disMissDialog();
            }

            @Override
            public void onProgressUpdate(float percentage) {
                runOnUiThread(() -> {
                    if ((int) (100 * percentage) <= 100)
                        progressDialog.setmProgressbar((int) (100 * percentage));
                });
            }
        });
    }

    private PLVideoSaveListener mVideoSaveListener = new PLVideoSaveListener() {
        @Override
        public void onSaveVideoSuccess(final String destFile) {
            isSaveing = false;
            runOnUiThread(() -> {
                progressDialog.disMissDialog();
                ToVideoPushActivity(destFile);
            });
        }

        @Override
        public void onSaveVideoFailed(int errorCode) {
            UIUtils.runOnUIThread(() -> {
                isSaveing = false;
                progressDialog.disMissDialog();
                mRlPush.setEnabled(true);
            });

        }

        @Override
        public void onSaveVideoCanceled() {
            isSaveing = false;
            progressDialog.disMissDialog();
            mRlPush.setEnabled(true);
        }


        @Override
        public void onProgressUpdate(final float percentage) {
            UIUtils.runOnUIThread(() -> {
                LogUtils.i("onProgressUpdate" + percentage);
                if ((int) (100 * percentage) <= 100)
                    progressDialog.setmProgressbar((int) (100 * percentage));
            });
        }
    };

    private void ToVideoPushActivity(String destFile) {

        //将视屏保存
        VideoHelper.getIntence().addMainVideoInfo(destFile);
        VideoHelper.getIntence().initGif(this, mShortVideoComposer, new OnInitGifListener() {
            @Override
            public void onStartGif() {
                if (progressDialog == null)
                    progressDialog = new ProgressDialog(PreViewActivity.this);
                progressDialog.setmProgressbar(50);
                progressDialog.show();
            }

            @Override
            public void onSuccessGif() {
                progressDialog.disMissDialog();
                toPublishVideo();
            }

            @Override
            public void onFailGif() {
                progressDialog.disMissDialog();
                toPublishVideo();
            }

            @Override
            public void onProgress(int progress) {
                progressDialog.setmProgressbar(progress);
            }
        });
    }

    private void toPublishVideo() {
        Intent intent = new Intent(PreViewActivity.this, VideoPublishActivity.class);
        startActivityForResult(intent, Constant.REQUESTCODE);
        mRlPush.setEnabled(true);
        onPause();//再次关闭资源
    }

    @Override
    public void onCompletion() {
        time = 0;
    }

    @Override
    public void onSaveVideoSuccess(String s) {
        isSaveing = false;
        runOnUiThread(() -> {
            progressDialog.disMissDialog();
            LogUtils.e(TAG, "点击保存时保存的视屏");
            mMp4path = s;
            if (handleType == 1) {
                saveVideo();
            }
            if (handleType == 2) {
                conposeVideo();
            }
        });


    }

    @Override
    public void onSaveVideoFailed(int i) {
        UIUtils.runOnUIThread(() -> {
            LogUtil.d(TAG, i + "进度");
            isSaveing = false;
            progressDialog.disMissDialog();
        });

    }

    @Override
    public void onSaveVideoCanceled() {
        UIUtils.runOnUIThread(() -> {
            isSaveing = false;
            progressDialog.disMissDialog();
        });

    }

    @Override
    public void onProgressUpdate(float percentage) {
        UIUtils.runOnUIThread(() -> {
            LogUtils.e(TAG, "onProgressUpdate" + percentage);
            if ((int) (100 * percentage) <= 100)
                progressDialog.setmProgressbar((int) (100 * percentage));
        });

    }

    @Override
    public void dissMissClick() {
        setVisibility(View.VISIBLE, mRlFinish, mRlPush, llToolsRight, mMeiHua, mSectionProgressBar);
    }

    @Override
    public void OnScrollBorder(float start, float end) {
        changeTime();
        LogUtils.e(TAG, "OnScrollBorder");
    }

    @Override
    public void onScrollStateChange() {
        calculateRange();
        LogUtils.e(TAG, "onScrollStateChange");
    }


    // 视频编辑器预览状态
    private enum PLShortVideoEditorStatus {
        Idle,
        Playing,
        Paused,
    }


    @Override
    public void getIntentData(Intent intent) {
        mMp4path = getIntent().getStringExtra(VideoHelper.VIDEO_PATH);
        if (TextUtils.isEmpty(mMp4path)) {
            finish();
            return;
        }

        //设置滤镜撤销栈
        VideoHelper.getIntence().setCommendFilterManger(new CommandManager());
        videoType = getIntent().getBooleanExtra(VideoHelper.VIDEO_LOCAL, false);
        videoRotate = getIntent().getBooleanExtra(VideoHelper.VIDEO_ROTATE, false);
        isLocal = videoType;
        Log.i(TAG, "editing file: " + mMp4path);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_preview;
    }

    @Override
    public void initView() {
        mPreviewView = findViewById(R.id.preview);
        mRlPush = findViewById(R.id.rl_push);
        llToolsRight = findViewById(R.id.ll_tools_right);
        mIvPre = findViewById(R.id.iv_pre);
        mIvNext = findViewById(R.id.iv_next);
        mIvClose = findViewById(R.id.iv_close);
        mMeiHua = findViewById(R.id.ll_mh);
        mRlFinish = findViewById(R.id.rl_finish);
        mLlBotton = findViewById(R.id.ll_bottom);
        thumbnailView = findViewById(R.id.thumbnailView);

        mRlViewJianji = findViewById(R.id.rl_view_jian_ji);
        mIvPlay = findViewById(R.id.iv_play);

        mFrameListView = findViewById(R.id.video_frame_list);
        mPrtotate = findViewById(R.id.pr_rotate_icon);
        mTvSave = findViewById(R.id.tv_save);
        mTvCancle = findViewById(R.id.tv_cancle);
        mIvSave = findViewById(R.id.iv_save);
        mIvCancle = findViewById(R.id.iv_cancle);
        mMore = findViewById(R.id.tv_time_more);
        mRlfs = findViewById(R.id.rl_fs);
        haveSelectTime = findViewById(R.id.tv_time_have);
        mPrtotate.setOnClickListener(this);
        mTvSave.setOnClickListener(this);
        mTvCancle.setOnClickListener(this);
        mPreviewView.setOnClickListener(this);
        mIvSave.setOnClickListener(this);
        mIvCancle.setOnClickListener(this);


        mMediaFile = new PLMediaFile(mMp4path);
        findViewById(R.id.ll_yf).setVisibility(View.INVISIBLE);
        mShortVideoTranscoder = new PLShortVideoTranscoder(getApplicationContext(), mMp4path, VideoHelper.VIDEO_STORAGE_DIR + System.currentTimeMillis() + LogonUtils.getProFildId() + "cos_fun.mp4");
        //监听裁剪器滑动
        thumbnailView.setOnScrollBorderListener(this);

        findViewById(R.id.pr_mei_hua).setOnClickListener(this);
        findViewById(R.id.pr_jj).setOnClickListener(this);
        findViewById(R.id.pr_yf).setOnClickListener(this);
        findViewById(R.id.ll_again_cos).setOnClickListener(this);
        mSectionProgressBar = findViewById(R.id.record_progressbar);
        findViewById(R.id.ll_jj).setOnClickListener(this);
        mRlPush.setOnClickListener(this);
        initShortVideoEditor();
        findViewById(R.id.ll_yf).setOnClickListener(this);
        mIvPre.setOnClickListener(this);
        mIvNext.setOnClickListener(this);
        mIvClose.setOnClickListener(this);
        mMeiHua.setOnClickListener(this);
        mRlFinish.setOnClickListener(this);
        mSectionProgressBar.setMax((int) mMixDuration);

        //根据拍摄的模式显示隐藏相关的控件,加载相应的资源
        initShootMode();
        //本地的视屏需要剪裁
        if (videoType || videoRotate) {
            isCutVideo = true;
        } else {
            isCutVideo = false;
        }
    }


    /**
     * 更改选择的裁剪区间的时间
     */
    private void changeTime() {
        float left = thumbnailView.getLeftInterval();
        float pro1 = left / thumbnailView.getWidth();

        mSelectedBeginMs = (int) (mMixDuration * pro1);

        float right = thumbnailView.getRightInterval();
        float pro2 = right / thumbnailView.getWidth();
        mSelectedEndMs = (int) (mMixDuration * pro2);
        LogUtils.e(TAG, mSelectedBeginMs + "+++++++++++++++>" + mSelectedEndMs);
    }

    /**
     * 根据拍摄的模式显示隐藏相关的控件,加载相应的资源
     */
    private void initShootMode() {
        mRlFinish.setVisibility(View.VISIBLE);
    }


    /**
     * 启动预览
     */
    private void startPlayback() {
        mIvPlay.setVisibility(View.GONE);
        if (isCutVideo) {
            mShortVideoEditor.seekTo((int) mSelectedBeginMs);
            LogUtils.e(TAG, "seekTo1" + mSelectedBeginMs);
            if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Idle) {
                mShortVideoEditor.startPlayback();
                mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
            } else if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Paused) {
                mShortVideoEditor.resumePlayback();
            }
            stopTrackPlayProgress();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mShortVideoEditor.getCurrentPosition() >= mSelectedEndMs) {
                        mShortVideoEditor.seekTo((int) mSelectedBeginMs);
                        LogUtils.e(TAG, "seekTo2" + mSelectedBeginMs);
                    }
                    mHandler.postDelayed(this, 100);
                }
            }, 100);
        } else {
            if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Idle) {
                mShortVideoEditor.startPlayback();
                mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
            } else if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Paused) {
                mShortVideoEditor.resumePlayback();
                mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
            }
        }


    }


    private void stopTrackPlayProgress() {
        mHandler.removeCallbacksAndMessages(null);
    }


    /**
     * 停止预览
     */
    private void stopPlayback(boolean isClick) {
        mShortVideoEditor.stopPlayback();
        if (isClick)
            mIvPlay.setVisibility(View.VISIBLE);
        mShortVideoEditorStatus = PLShortVideoEditorStatus.Idle;
    }

    /**
     * 暂停预览
     *
     * @param isClick
     */
    private void pausePlayback(boolean isClick) {
        mShortVideoEditor.pausePlayback();
        if (isClick)
            mIvPlay.setVisibility(View.VISIBLE);
        mShortVideoEditorStatus = PLShortVideoEditorStatus.Paused;
    }


    /**
     * 预览配置参数
     */
    private void initShortVideoEditor() {
        mShortVideoComposer = new PLShortVideoComposer(this);
        setting = new PLVideoEditSetting();
        setting.setSourceFilepath(mMp4path);
        if (!isLocal) {
            setting.setKeepOriginFile(true);
        } else {
            setting.setKeepOriginFile(true);
        }
        setting.setDestFilepath(VideoHelper.VIDEO_SHOOT + System.currentTimeMillis() + LogonUtils.getProFildId() + "cos_fun.mp4");
        mShortVideoEditor = new PLShortVideoEditor(mPreviewView, setting);
        mShortVideoEditor.setDisplayMode(PLDisplayMode.FULL);
        mMixDuration = mShortVideoEditor.getDurationMs();
        mSelectedBeginMs = 0;
        mSelectedEndMs = mMixDuration;
        mShortVideoEditor.setVideoPlayerListener(this);
        mShortVideoEditor.setVideoSaveListener(this);

        if (VideoHelper.getIntence().isFanPai()) {
            mShortVideoEditor.setAudioMixFile(VideoHelper.getIntence().getVideoAudioPath());
            mShortVideoEditor.setAudioMixLooping(false);
            mShortVideoEditor.muteOriginAudio(true);
        }
        startTimer();
        //初始化美化的弹窗
        beautifyDialog = new BeautifyDialog(this, null, mShortVideoEditor, 2);
        beautifyDialog.setOnDialogDissMissListener(this);
        progressDialog = new ProgressDialog(this);


    }

    private long time = 0;

    private void startTimer() {
        timerTask = new Timer();
        taskTimer = new TimerTask() {
            @Override
            public void run() {
                time = time + 10;
                if (time>=mMixDuration)time=0;
                runOnUiThread(() -> {
                    if (mSectionProgressBar != null)
                        mSectionProgressBar.setProgress((int) time);
                });
            }
        };
        timerTask.schedule(taskTimer, 0, 10);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.TYPE_VIDEO:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    LocalMedia localMedia = selectList.get(0);
                    if (!TextUtils.isEmpty(localMedia.getPath())) {
                        if (localMedia.getDuration() > (1000 * 60 * 30)) {
                            showHintDialog("视频大于30分钟,请重新选择!");
                            return;
                        }
                        String desPath = VideoHelper.VIDEO_STORAGE_DIR + System.currentTimeMillis() + LogonUtils.getProFildId() + "cos_fun.mp4";
                        try {
                            FileUtils.copyFile2DestPath(localMedia.getPath(), desPath);
                        } catch (IOException e) {
                            e.printStackTrace();
                            ToastUtils.showToast("视屏拷贝失败!");
                            return;
                        }
                        mMp4path = desPath;
                        Intent intent = new Intent(PreViewActivity.this, PreViewActivity.class);
                        intent.putExtra(VideoHelper.VIDEO_PATH, desPath);
                        intent.putExtra(VideoHelper.VIDEO_LOCAL, isLocal);
                        startActivity(intent);
                        finish();
                    } else {
                        finish();
                    }
                    break;
                case Constant.REQUESTCODE:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        } else if (resultCode == 0 && requestCode == 2) {
            finish();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        CutOutVideo(isCutVideo);
        startPlayback();
        initFilterCommandManger();
    }

    public void initFilterCommandManger() {
        CommandManager commendFilterManger = VideoHelper.getIntence().getCommendFilterManger();
        if (commendFilterManger == null) return;
        if (commendFilterManger.isCanRedo()) {
            mIvNext.setImageDrawable(getResources().getDrawable(R.drawable.next_icon));
            mIvNext.setEnabled(true);
        } else {
            mIvNext.setEnabled(false);
            mIvNext.setImageDrawable(getResources().getDrawable(R.drawable.next_icon_press));
        }

        if (commendFilterManger.isCanUndo()) {
            mIvPre.setImageDrawable(getResources().getDrawable(R.drawable.previous_icon));
            mIvPre.setEnabled(true);
        } else {
            mIvPre.setImageDrawable(getResources().getDrawable(R.drawable.previous_icon_press));
            mIvPre.setEnabled(false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausePlayback(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlayback(false);
        if (mShortVideoEditor != null) {
            mShortVideoEditor.pausePlayback();
        }
        if (taskTimer != null) {
            taskTimer.cancel();
            taskTimer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (progressDialog != null) {
            progressDialog.disMissDialog();
        }

        VideoHelper.getIntence().setCommendFilterManger(null);
    }

    /**
     * 剪裁
     *
     * @param isCut
     */
    public void CutOutVideo(boolean isCut) {
        if (isCut) {
            mLlBotton.setVisibility(View.GONE);
            mIvClose.setVisibility(View.GONE);
            llToolsRight.setVisibility(View.GONE);
            mSectionProgressBar.setVisibility(View.GONE);
            mIvPre.setVisibility(View.GONE);
            mIvNext.setVisibility(View.GONE);
            mRlViewJianji.setVisibility(View.VISIBLE);
            if (isLocal) {
                setVisibility(View.VISIBLE, mIvSave, mIvCancle);
                setVisibility(View.GONE, mTvSave, mTvCancle);

            } else {
                setVisibility(View.GONE, mIvSave, mIvCancle);
                setVisibility(View.VISIBLE, mTvSave, mTvCancle);
            }
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.leftMargin = DesityUtils.dp2px(40);
            layoutParams.rightMargin = DesityUtils.dp2px(40);
            layoutParams.bottomMargin = DesityUtils.dp2px(130);
            layoutParams.topMargin = DesityUtils.dp2px(50);
            mPreviewView.setLayoutParams(layoutParams);
            initVideoFrameList();
        } else {
            mLlBotton.setVisibility(View.VISIBLE);
            mIvClose.setVisibility(View.VISIBLE);
            llToolsRight.setVisibility(View.VISIBLE);
            mSectionProgressBar.setVisibility(View.VISIBLE);
            mIvPre.setVisibility(View.VISIBLE);
            mIvNext.setVisibility(View.VISIBLE);
            mRlViewJianji.setVisibility(View.GONE);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mPreviewView.setLayoutParams(layoutParams);
        }

    }

    private static final int SLICE_COUNT = 8;
    private long mSelectedBeginMs;
    private long mSelectedEndMs;
    private int mSlicesTotalLength;

    private void initVideoFrameList() {
        mMore.setText("截选视屏,最长" + StringUtils.div(60000 - VideoHelper.getIntence().getVideoListTime(), 1000, 1) + "s,");
        haveSelectTime.setText("已选" + StringUtils.div((mMixDuration), 1000, 1) + "秒");
        canHave = 60000 - VideoHelper.getIntence().getVideoListTime();
        if (mMixDuration > 60000) {
            showToast("剪裁的视屏不能大于" + canHave / 1000 + "s");
            mTvSave.setTextColor(getResources().getColor(R.color.white_alpha_40));
            mTvSave.setEnabled(false);
            mIvSave.setEnabled(false);
        } else {
            mTvSave.setTextColor(getResources().getColor(R.color.white));
            mTvSave.setEnabled(true);
            mIvSave.setEnabled(true);
        }
        mFrameListView.removeAllViews();
        mFrameListView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mFrameListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                final int sliceEdge = mFrameListView.getWidth() / SLICE_COUNT;
                mSlicesTotalLength = sliceEdge * SLICE_COUNT;
                LogUtils.d("slice edge: " + sliceEdge);
                final float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, getResources().getDisplayMetrics());

                class MyTask extends AsyncTask<Void, PLVideoFrame, Void> {

                    @Override
                    protected Void doInBackground(Void... voids) {
                        for (int i = 0; i < SLICE_COUNT; ++i) {
                            PLVideoFrame frame = mMediaFile.getVideoFrameByTime((long) ((1.0f * i / SLICE_COUNT) * mMixDuration), true, sliceEdge, sliceEdge);
                            publishProgress(frame);
                        }
                        return null;
                    }

                    @Override
                    protected void onProgressUpdate(PLVideoFrame... values) {
                        super.onProgressUpdate(values);
                        PLVideoFrame frame = values[0];
                        if (frame != null) {
                            View root = LayoutInflater.from(PreViewActivity.this).inflate(R.layout.frame_item, null);

                            int rotation = frame.getRotation();
                            ImageView thumbnail = root.findViewById(R.id.thumbnail);
                            thumbnail.setImageBitmap(frame.toBitmap());
                            thumbnail.setRotation(rotation);
                            FrameLayout.LayoutParams thumbnailLP = (FrameLayout.LayoutParams) thumbnail.getLayoutParams();
                            if (rotation == 90 || rotation == 270) {
                                thumbnailLP.leftMargin = thumbnailLP.rightMargin = (int) px;
                            } else {
                                thumbnailLP.topMargin = thumbnailLP.bottomMargin = (int) px;
                            }
                            thumbnail.setLayoutParams(thumbnailLP);

                            LinearLayout.LayoutParams rootLP = new LinearLayout.LayoutParams(sliceEdge, sliceEdge);
                            mFrameListView.addView(root, rootLP);
                        }
                    }
                }
                new MyTask().execute();
            }
        });

    }

    private void calculateRange() {
        haveSelectTime.setText("已选" + StringUtils.div((mSelectedEndMs - mSelectedBeginMs), 1000, 1) + "秒");
        LogUtils.e(TAG, "new range: " + mSelectedBeginMs + "-" + mSelectedEndMs);

        mMore.setText("截选视屏,最长" + StringUtils.div(canHave, 1000, 1) + "s,");
        if (StringUtils.div((mSelectedEndMs - mSelectedBeginMs), 1000, 1) > canHave / 1000) {
            showToast("剪裁的视屏不能大于" + canHave / 1000 + "s");
            mTvSave.setTextColor(getResources().getColor(R.color.white_alpha_40));
            mTvSave.setEnabled(false);
            mIvSave.setEnabled(false);
        } else if (StringUtils.div((mSelectedEndMs - mSelectedBeginMs), 1000, 1) < 0.5) {
            showToast("剪裁的视屏不能小于0.5s");
            mTvSave.setTextColor(getResources().getColor(R.color.white_alpha_40));
            mTvSave.setEnabled(false);
            mIvSave.setEnabled(false);
        } else {
            mTvSave.setEnabled(true);
            mIvSave.setEnabled(true);
            mTvSave.setTextColor(getResources().getColor(R.color.white));
        }
        startPlayback();
        LogUtils.d("begin mSelectedEndMs: " + mSelectedEndMs + " end mSelectedBeginMs: " + mSelectedBeginMs);
    }

    public void onDone() {

        LogUtils.d("trim to file path: " + VideoHelper.TRIM_FILE_PATH + " range: " + mSelectedBeginMs + " - " + mSelectedEndMs);
        if (progressDialog == null) progressDialog = new ProgressDialog(this);
        progressDialog.show();
        mShortVideoTrimmer = new PLShortVideoTrimmer(this, mMp4path, VideoHelper.TRIM_FILE_PATH + System.currentTimeMillis() + "trimmed.mp4");
        mShortVideoTrimmer.trim(mSelectedBeginMs, mSelectedEndMs, PLShortVideoTrimmer.TRIM_MODE.ACCURATE, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String path) {
                isSaveing = false;
                runOnUiThread(() -> {
                    progressDialog.disMissDialog();
                    LogUtils.e(TAG, "剪切完成,地址为:" + path);
                    progressDialog.disMissDialog();
                    CutOutVideo(false);
                    isCutVideo = true;
                    if (!TextUtils.equals(mMp4path, path)) {
                        FileUtil.deleteFile(mMp4path);//删除原先的视屏(不切的话就用原先的视屏)
                    }
                    LogUtils.e(TAG, "地址重新赋值完成,地址为:mMp4path" + mMp4path);
                    startPlayback();
                    //因为sdk不支持重新赋值,所以需要跳转页面达到再次赋值的效果
                    setNewVideoPath(path);

                });
            }

            @Override
            public void onSaveVideoFailed(final int errorCode) {
                isSaveing = false;
                runOnUiThread(() -> {
                    progressDialog.disMissDialog();
                    ToastUtils.showToast(errorCode);
                });
            }

            @Override
            public void onSaveVideoCanceled() {
                isSaveing = false;
                progressDialog.disMissDialog();

            }

            @Override
            public void onProgressUpdate(final float percentage) {
                runOnUiThread(() -> progressDialog.setmProgressbar((int) (100 * percentage)));
            }
        });
    }


    private float clamp(float origin) {
        if (origin < 0) {
            return 0;
        }
        if (origin > 1) {
            return 1;
        }

        return origin;
    }

//    @Override
//    public void onBackPressed() {
//        if (isSaveing) {
//            if (mShortVideoComposer!= null) {
//                mShortVideoComposer.cancelComposeVideos();
//                mShortVideoComposer.cancelComposeToGIF();
//                progressDialog.disMissDialog();
//            }
//
//            if (mShortVideoEditor!=null) {
//                mShortVideoEditor.cancelSave();
//                progressDialog.disMissDialog();
//            }
//
//            if (mShortVideoTrimmer!= null) {
//                mShortVideoTrimmer.cancelTrim();
//                progressDialog.disMissDialog();
//            }
//        }else {  super.onBackPressed();}
//
//    }

    //禁止使用返回键返回到上一页,但是可以直接退出程序**
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;//不执行父类点击事件
        }
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }

    /**
     * 关闭本地选择
     */
    public void finishCommonActivity() {
//        if (CommonActivity.instance != null) {
//            CommonActivity.instance.finish();
//        }
    }


    /**
     * 重新设置地址
     * @param videoPath
     */
    private void setNewVideoPath(String videoPath){
        if (setting!=null) {
            setting=null;
        }
        setting = new PLVideoEditSetting();
        setting.setSourceFilepath(videoPath);
        if (!isLocal) {
            setting.setKeepOriginFile(true);
        } else {
            setting.setKeepOriginFile(true);
        }
        setting.setDestFilepath(VideoHelper.VIDEO_SHOOT + System.currentTimeMillis() + LogonUtils.getProFildId() + "cos_fun.mp4");
//        mShortVideoEditor = new PLShortVideoEditor(mPreviewView);
        mShortVideoEditor.setVideoEditSetting(setting);
        mShortVideoEditor.setDisplayMode(PLDisplayMode.FULL);
//        mMixDuration = mShortVideoEditor.getDurationMs();
         mMediaFile= new PLMediaFile(videoPath);
        mMixDuration =  mMediaFile.getDurationMs();
        mSelectedBeginMs = 0;
        mSelectedEndMs = mMixDuration;
        startPlayback();
        mMp4path= videoPath;
        timerTask = null;
        taskTimer = null;
        LogUtils.e("countDownTimer444444", time + "");
        startTimer();
        mRlfs.removeViewAt(1);
        ThumbnailView thumbnailView = new ThumbnailView(this);
        mRlfs.addView(thumbnailView,1);
        thumbnailView.setOnScrollBorderListener(this);
    }
}
